package com.example.blog.controller;

import com.example.blog.entity.Article;
import com.example.blog.entity.User;
import com.example.blog.service.ArticleService;
import com.example.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/articles")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private UserService userService;

    // 注意：由于移除了Spring Security，此处使用简化的用户认证
    // 实际应用中需要根据认证方式调整
    @PostMapping
    public ResponseEntity<?> createArticle(@RequestBody Map<String, Object> request) {
        try {
            // 获取用户信息（简化处理）
            String username = (String) request.get("username");
            if (username == null || username.isEmpty()) {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("error", "用户名不能为空");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMap);
            }

            User user = userService.findByUsername(username);
            if (user == null) {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("error", "用户不存在");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMap);
            }

            // 构建文章对象
            Article article = new Article();
            article.setTitle((String) request.get("title"));
            article.setContent((String) request.get("content"));
            // 设置其他属性...

            Article createdArticle = articleService.createArticle(article, user);
            return ResponseEntity.status(HttpStatus.CREATED).body(createdArticle);
        } catch (RuntimeException e) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMap);
        }
    }

    @GetMapping
    public ResponseEntity<List<Article>> getAllArticles() {
        List<Article> articles = articleService.findAllOrderByCreateTimeDesc();
        return ResponseEntity.ok(articles);
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getArticleById(@PathVariable Long id) {
        try {
            Article article = articleService.findById(id);
            // 增加浏览量
            articleService.increaseViewCount(id);
            return ResponseEntity.ok(article);
        } catch (RuntimeException e) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorMap);
        }
    }

    // 注意：由于移除了Spring Security，此处使用简化的权限验证
    @PutMapping("/{id}")
    public ResponseEntity<?> updateArticle(@PathVariable Long id, @RequestBody Map<String, Object> request) {
        try {
            // 获取用户信息
            String username = (String) request.get("username");
            if (username == null || username.isEmpty()) {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("error", "用户名不能为空");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMap);
            }

            User user = userService.findByUsername(username);
            if (user == null) {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("error", "用户不存在");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMap);
            }

            // 检查权限
            Article existingArticle = articleService.findById(id);
            if (!existingArticle.getUser().getId().equals(user.getId())) {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("error", "无权修改此文章");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorMap);
            }

            // 更新文章信息
            Article article = new Article();
            article.setId(id);
            article.setTitle((String) request.get("title"));
            article.setContent((String) request.get("content"));
            // 设置其他属性...

            Article updatedArticle = articleService.updateArticle(article);
            return ResponseEntity.ok(updatedArticle);
        } catch (RuntimeException e) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMap);
        }
    }

    // 注意：由于移除了Spring Security，此处使用简化的权限验证
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteArticle(@PathVariable Long id, @RequestParam String username) {
        try {
            if (username == null || username.isEmpty()) {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("error", "用户名不能为空");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMap);
            }

            User user = userService.findByUsername(username);
            if (user == null) {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("error", "用户不存在");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMap);
            }

            // 检查权限
            Article article = articleService.findById(id);
            if (!article.getUser().getId().equals(user.getId())) {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("error", "无权删除此文章");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorMap);
            }

            articleService.deleteArticle(id);
            Map<String, Object> successMap = new HashMap<>();
            successMap.put("message", "文章删除成功");
            return ResponseEntity.ok(successMap);
        } catch (RuntimeException e) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorMap);
        }
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Article>> getArticlesByUserId(@PathVariable Long userId) {
        List<Article> articles = articleService.findByUserId(userId);
        return ResponseEntity.ok(articles);
    }

    @GetMapping("/search")
    public ResponseEntity<List<Article>> searchArticles(@RequestParam String keyword) {
        List<Article> articles = articleService.searchByTitle(keyword);
        return ResponseEntity.ok(articles);
    }

    @GetMapping("/category/{categoryId}")
    public ResponseEntity<List<Article>> getArticlesByCategory(@PathVariable Long categoryId) {
        List<Article> articles = articleService.findByCategoryId(categoryId);
        return ResponseEntity.ok(articles);
    }

    @PostMapping("/{id}/like")
    public ResponseEntity<?> likeArticle(@PathVariable Long id) {
        try {
            Article article = articleService.increaseLikeCount(id);
            Map<String, Object> successMap = new HashMap<>();
            successMap.put("message", "点赞成功");
            successMap.put("likeCount", article.getLikeCount());
            return ResponseEntity.ok(successMap);
        } catch (RuntimeException e) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorMap);
        }
    }

}